package com.kongxx.wicketstudy.tutorial.login;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;

import com.kongxx.wicketstudy.tutorial.Home;

public final class Login extends WebPage {
	public Login(final PageParameters parameters) {
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);
		
		add(new LoginForm("loginForm"));
	}

	public final class LoginForm extends Form {
		private final ValueMap properties = new ValueMap();

		public LoginForm(final String id) {
			super(id);
			
			add(new TextField("username", new PropertyModel(properties, "username")));
			add(new PasswordTextField("password", new PropertyModel(properties, "password")));
		}

		public final void onSubmit() {
			LoginSession session = (LoginSession)getSession();

			if (session.authenticate(properties.getString("username"), properties.getString("password"))) {
				if (!continueToOriginalDestination()) {
					setResponsePage(Home.class);
				}
			} else {
				final String errmsg = "Failed to login!";
				error(errmsg);
			}
		}
	}
}